System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

91% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Day 9: Streaming & Big Data
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Day 10: Software Infrastructure
Design a Code Deployment System
Design an API Gateway
Day 11: Distributed Compute & Intelligence
Design Amazon Lambda
Design ChatGPT
Day 12: Search, Indexing & Retrieval Systems
Design Typeahead/Autocomplete
Design Google Search
Day 13: Location & Booking Services
Design AirBnB
Design Uber/Lyft
Day 14: Coordination & Configuration
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design a Distributed Lock Manager (like Chubby)
Image

Here is a detailed, step-by-step design for a Distributed Lock Manager (DLM) similar to Google’s Chubby.

1. Problem Definition and Scope

We are designing a distributed lock service and coordination system. It serves as the "root of trust" for a distributed architecture, allowing thousands of other systems (like databases, load balancers, and job schedulers) to elect leaders and store small, critical configuration files.

  • User Groups: Internal software services and infrastructure systems (not human end-users).

  • Main Actions: Leader election (acquiring a lock), storing metadata (e.g., "who is the primary database?"), and listening for changes (events).

  • Scope:

    • We will focus on coarse-grained locking. Locks are held for seconds or days, not milliseconds.
    • We will focus on Strong Consistency. All nodes must see the same state; stale data is not acceptable for locking.
    • We will not design a high-throughput message queue or a general-purpose file storage system for large blobs.
Image

2. Clarify functional requirements

Must Have

  • Lock Acquisition: Clients can acquire an exclusive lock on a named node (file).

  • Session Management: The system must maintain an active session for each client via heartbeats. If a client dies, its locks are automatically released.

  • Metadata Storage: Clients can read and write small files (under 1MB) organized in a directory hierarchy.

  • Events/Watches: Clients can subscribe to a node and receive notifications when it changes or is deleted.

  • Reliable Reads: Clients can read data with a guarantee that it is the most current version.

Nice to Have

  • Recursive Locks: Locking a directory covers all nodes inside it.

  • ACLs: Permission controls (who can read/write).

  • Sequencers: A monotonic number returned with the lock to prevent "zombie" writes (fencing).

Image

3. Clarify non-functional requirements

  • Target Users: 10,000+ active clients (servers) per cluster.

  • Read vs. Write: Extremely Read Heavy (1000:1). Configuration changes and leader failovers are rare; reading the config is frequent.

  • Latency:

    • Writes: Moderate (50ms - 500ms) as they require consensus across multiple nodes.
    • Reads: Very low (< 5ms), ideally served from local client cache.
  • Availability: High (99.99%). If the lock manager is down, the entire datacenter usually stalls.

  • Consistency: Strong (CP in CAP theorem). We prefer the system to be unavailable rather than returning incorrect locking data (Split Brain).

  • Data Size: Small. The entire dataset usually fits in RAM (e.g., < 10GB).

Image

4. Back of the envelope estimates

  • Traffic Estimates:
    • Assume 10,000 connected clients.
    • Each client sends a heartbeat (KeepAlive) every 10 seconds.
    • Heartbeat QPS = 10,000 / 10 = 1,000 QPS. This is a steady background load.
    • Read QPS: High (e.g., 50,000 QPS), but mostly served by client-side cache.
    • Write QPS: Low (e.g., 50 - 100 QPS).
  • Storage Estimates:
    • Assume 1 million nodes (files/locks).
    • Average node size = 1 KB.
    • Total Storage = 1,000,000 * 1 KB = 1 GB.
    • Conclusion: We can keep the entire tree in RAM for speed, using disk only for durability (logs).
  • Bandwidth:
    • Payloads are small text/binary. Bandwidth is not a bottleneck; request processing (CPU) is.
Image

5. API design

We will use a gRPC-style API (or internal RPC) rather than REST, as it fits the session-oriented nature better.

1. CreateSession

  • Method: POST /session/create
  • Response: session_id, keep_alive_interval (e.g., 10s).

2. KeepAlive

  • Method: POST /session/renew
  • Params: session_id
  • Response: status (OK/EXPIRED).

3. AcquireLock (Create Ephemeral Node)

  • Method: POST /node/create
  • Params: path (e.g., "/db/leader"), content, mode (EPHEMERAL)
  • Response: status (SUCCESS/ALREADY_EXISTS), sequencer (version).

4. GetNode

  • Method: GET /node
  • Params: path, watch (boolean)
  • Response: content, stat, lock_holder.
  • Behavior: If watch=true, the connection registers a callback. The server will notify the client later if the node changes.

5. SetContent

  • Method: PUT /node
  • Params: path, content, expected_version (for optimistic locking).
  • Response: new_version.

6. High level architecture

Our architecture follows a "Replicated State Machine" model using a consensus protocol like Raft or Paxos.

Client App -> Client Library -> Load Balancer -> DLM Cell (Cluster)

  1. Client Application: The service using the lock (e.g., a MySQL server).

  2. Client Library: A "smart" library linked into the application. It handles:

    • Caching: Stores file content in local RAM.
    • Heartbeats: Automatically sends KeepAlives for the session.
    • Master Redirection: Remembers who the Leader is to avoid unnecessary hops.
  3. DLM Cell (The Cluster): A group of 5 servers.

    • The Leader: One node is elected Leader. All writes and lock acquisitions go here.
    • The Followers (4 nodes): They replicate the Leader's log. If the Leader dies, they elect a new one.
  4. Consensus Module: The logic (Raft/Paxos) ensuring all 5 nodes agree on the order of operations.

  5. Storage: In-memory tree structure backed by a Write-Ahead Log (WAL) on disk.

Image

7. Data model

We use a hierarchical tree structure similar to a UNIX filesystem.

Storage Engine: In-Memory Tree

The entire database lives in RAM.

  • Root /
    • ls (Lock Service)
      • global
        • master_db (Node)
          • Content: "10.0.0.5"
          • Type: Ephemeral (Lock)
          • ACL: [Read:All, Write:DB_Admins]
          • Watchers: [Client_A, Client_B]

Why In-Memory?

  • Since the data is small (1GB), RAM is cheap and provides the fastest access.
  • We do not need complex SQL joins. We just need path lookups (/ls/global/master_db).

Durability:

  • WAL (Write Ahead Log): Every change (create, delete, write) is appended to a file on disk before updating the RAM.
  • Snapshot: Every few hours, the RAM state is saved to a file so we can truncate the log.

8. Core flows end to end

These flows describe exactly how the Distributed Lock Manager (DLM) handles its three most critical jobs: deciding who is in charge (locking), guaranteeing data accuracy (consistency), and cleaning up failures (session management).

This design prioritizes Strong Consistency (CP). The system would rather be slow or unavailable than lie to a client about who holds a lock.

Flow 1: Leader Election (Acquiring a Lock)

This flow explains how distributed processes coordinate to ensure only one leader exists at a time. It relies on the concept of Ephemeral Nodes (files that disappear when the creator disconnects).

The Scenario:

Imagine you have three database servers (Clients A, B, and C). They all boot up at the same time, and each wants to be the "Primary" database.

The Step-by-Step Process:

  1. The Race: All three clients immediately send a Create request to the DLM Leader.

    • Path: /election/master
    • Mode: EPHEMERAL (This ensures if the winner crashes, the lock is automatically released).
  2. Consensus (The Bottleneck): The DLM Leader receives the requests. Let's assume Client A's request arrives 1 millisecond before the others.

    • The Leader does not decide instantly. It proposes Client A's "Create" operation to its internal cluster (the 5 Raft nodes).
  3. Commit: The operation is written to the disk logs of at least 3 out of 5 DLM nodes. Once the majority agrees, the Leader "commits" the creation of the node.

  4. The Result:

    • Winner (Client A): The DLM returns SUCCESS. Client A creates a local "I am Leader" flag and starts working.
    • Losers (Client B & C): The DLM processes their requests next. It sees /election/master already exists. It returns ALREADY_EXISTS.
  5. Watch: The losers don't just give up; they become "Slaves." They immediately subscribe (Watch) to the /election/master node so they can take over if Client A dies.

Image

Flow 2: Smart Reads with Blocking Invalidation

This is the most unique and complex part of this design (inspired heavily by Google's Chubby). It explains how we allow clients to cache data locally (for speed) without ever showing them old/stale data.

The Scenario:

  • Client A (Leader) wants to update a configuration file /config.
  • Client B (Slave) has previously read /config and has it stored in its local RAM (Cache).

The Problem:

If Client A updates the value on the server, Client B might still be reading its old local cached version. In a lock system, this "split-brain" view is dangerous.

The Step-by-Step Process:

  1. Update Request: Client A sends SetContent("/config", "new_value") to the DLM Leader.

  2. Detection: The DLM Leader checks its memory and sees that Client B has a registered "Cache Subscription" on /config.

  3. The BLOCK (Crucial Step): The DLM Leader pauses Client A's request. It does not write the new data yet. The request hangs.

  4. Invalidation: The DLM Leader sends a high-priority Invalidate("/config") message to Client B.

  5. Client Cleanup:

    • Client B receives the message.
    • It deletes /config from its local RAM.
    • It sends an Ack (Acknowledgement) back to the DLM Leader.
  6. Completion:

    • The DLM Leader receives the Ack. It knows nobody holds stale data anymore.
    • It commits the "new_value" via Raft.
    • It finally returns SUCCESS to Client A.
  7. Refetch: The next time Client B needs the config, it finds its cache empty, requests it from the server, and gets the "new_value".

Note: This makes Writes slower (latency penalty) to ensure Reads are consistent and fast.

Image

Flow 3: Session Expiry (The Safety Net)

This flow ensures that if a locked resource (like a database leader) crashes, the lock is eventually released so others can take over.

The Scenario:

Client A holds the Master Lock (Ephemeral Node). Client A's power cord is pulled. It cannot send a "Release Lock" command.

The Step-by-Step Process:

  1. The Lease: When Client A connected, it established a session with a Time-To-Live (TTL), e.g., 20 seconds.

  2. Heartbeats: Normally, Client A sends a "KeepAlive" every 10 seconds. Each KeepAlive resets the 20-second timer on the DLM.

  3. The Crash: Client A dies. The heartbeats stop.

  4. The Countdown: The DLM Leader keeps checking the timer. 10s pass... 15s pass... 20s pass.

  5. Session Death: The timer hits zero. The DLM marks Client A's session as EXPIRED.

  6. Cleanup (Garbage Collection):

    • The DLM finds all Ephemeral Nodes associated with Client A's session ID.
    • It deletes /election/master.
  7. Notification: Because Client B was "Watching" that node (from Flow 1), the DLM sends a NodeDeleted event to Client B.

  8. New Election: Client B sees the lock is gone and immediately triggers Flow 1 again to become the new Master.

Image

9. Caching and read performance

  • Strategy: Aggressive Client-Side Caching.

  • Consistency: We do not use TTL (e.g., "cache for 60s") because it allows stale reads. We use invalidation.

  • Impact: This means reads are effectively free (local RAM lookup) as long as the data doesn't change.

  • Trade-off: Writes are slower because the Leader must contact cached clients before finishing the write. This is acceptable because configuration data changes rarely.

10. Storage, indexing and media

  • Primary Storage: In-Memory Tree (Trie or Hash Map).

  • Disk: SSDs are required for the Write-Ahead Log to ensure low latency for writes (fsync).

  • Media: We reject large files. The API enforces a 1MB limit.

    • Alternative: If a user needs to lock a large asset (e.g., a database file), they store the file in Object Storage (S3) and store the path/URL in the DLM.
  • Indexing: Purely by path. No secondary indexes (e.g., "Find all locks created by User X") are maintained to keep the system simple and fast.

11. Scaling strategies

  • Initial Scale: A single 5-node cell handles 10k-20k clients easily due to caching.

  • Proxy Layer (Growing to 100k+ clients):

    • Directly connecting 100k clients to the Leader is hard (TCP limits, heartbeat storm).
    • We introduce Proxies.
    • Clients connect to Proxies.
    • Proxies aggregate heartbeats (batching) and forward them to the Leader.
    • Proxies cache reads. Invalidation messages go Leader -> Proxy -> Clients.
  • Partitioning (Federation):

    • We cannot shard a single consensus domain easily.
    • We scale by adding Cells based on namespace.
    • /ls/us-east/ lives in Cell A.
    • /ls/us-west/ lives in Cell B.

12. Reliability, failure handling and backpressure

  • Leader Failure:
    • If the Leader fails, followers detect silence.
    • A new election (Raft) picks a new Leader in ~1-2 seconds.
    • Jeopardy: During this switch, sessions are in "Jeopardy." The new Leader gives clients a Grace Period (e.g., 45s) to reconnect and prove they are alive before deleting their locks.
  • Fencing Tokens:
    • If a process hangs (GC pause) and loses its lock, it might wake up and try to write to the DB.
    • The DLM provides a sequencer (integer). The DB checks: "Is this write request's sequencer higher than the last one I saw?" If not, it rejects the write.
  • Backpressure:
    • If the system is overloaded, it rejects KeepAlive requests. This causes sessions to drop and locks to release, essentially resetting the system to a safe state rather than persisting in a degraded/incorrect state.

13. Security, privacy and abuse

  • Authentication: Mutual TLS (mTLS). Every client must present a valid certificate signed by the internal CA.

  • ACLs: Every node has an Access Control List stored with it.

    • e.g., /mysql/master: Read: All, Write: MySQL_Service_Account.
  • Abuse Prevention:

    • Quotas: Limit the total storage (e.g., 10MB) and node count (e.g., 5,000) per project.
    • Rate Limiting: Throttle clients who request locks too aggressively.

14. Bottlenecks and next steps

  • Bottleneck: The Single Leader.
    • Since all writes go to one node, write throughput is capped (likely < 5k writes/sec).
    • Next Step: This is usually fine for a lock manager. If needed, split workloads into different Cells (Namespace sharding).
  • Bottleneck: Invalidation Storms.
    • If a widely used config file changes, the Leader must notify thousands of clients.
    • Next Step: Use the Proxy layer to multicast these invalidations, reducing the CPU load on the Leader.

Summary

  • We prioritized Consistency and Reliability over speed.
    • We used Raft/Paxos for consensus.
    • We used Smart Clients with Blocking Invalidation to provide safe, cached reads.
    • We used Sessions with Ephemeral Nodes to handle client failures gracefully.
Design Uber/Lyft
Design a Distributed Job Scheduler (like Cron)
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Flow 1: Leader Election (Acquiring a Lock)

Flow 2: Smart Reads with Blocking Invalidation

Flow 3: Session Expiry (The Safety Net)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary